<template>
  <div class="mobile-app">
    <header class="header">
      <div class="header-content">
        <h1>宠物商城</h1>
      </div>
    </header>

    <div class="content">
      <aside class="sidebar">
        <ul class="category-list">
          <li v-for="(item, index) in categoryList" :key="index" class="category-item"
            :class="{ active: selectedCategory === index }" @click="handleCategoryClick(index)">
            {{ item.goodsName }}
          </li>
        </ul>
      </aside>

      <main class="product-grid">
        <div v-for="(item, index) in categoryProducts" :key="index" class="product-item"
          @click="goToProductList(item.id, item.name)">
          <div class="product-item-image">
            <img :src="item.pic" alt="">
          </div>
          <div class="product-item-title">{{ item.name }}</div>
        </div>
      </main>
    </div>

    <footer class="footer">
      <TabNav />
    </footer>
  </div>
  <div class="cart-block" @click="handleCartClick" @touchstart="startDrag" @touchmove="onDrag" @touchend="endDrag"
    ref="cartButton">
    <svg width="24" height="24" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
      <path d="M39 32H13L8 12H44L39 32Z" fill="#f3f0ff" />
      <path d="M3 6H6.5L8 12M8 12L13 32H39L44 12H8Z" stroke="#8a57f5" stroke-width="4" stroke-linecap="round"
        stroke-linejoin="round" />
      <circle cx="13" cy="39" r="3" stroke="#8a57f5" stroke-width="4" stroke-linecap="round" stroke-linejoin="round" />
      <circle cx="39" cy="39" r="3" stroke="#8a57f5" stroke-width="4" stroke-linecap="round" stroke-linejoin="round" />
    </svg>
  </div>
  <!-- 登录确认弹窗 -->
  <div v-if="showLoginConfirm" class="login-confirm-overlay" @click="closeLoginConfirm">
    <div class="login-confirm-dialog" @click.stop>
      <div class="login-confirm-content">
        <div class="login-confirm-title">您当前未登录</div>
        <div class="login-confirm-text">登录后才能使用该功能</div>
        <div class="login-confirm-buttons">
          <button class="login-btn" @click="goToLogin">去登录</button>
          <button class="cancel-btn" @click="closeLoginConfirm">再看看</button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
defineOptions({
  name: 'PetStoreIndex',
})

import { ref, onMounted, } from 'vue'
import TabNav from '@/components/TabNav/TabNav.vue'
import { getCategoryList, getCategoryDetail } from '@/views/petStore/api/index'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user';
import { showToast } from 'vant';

const userStore = useUserStore();
// 添加响应式状态
const selectedCategory = ref(0) // 默认选中第一个分类
const categoryList = ref([])
const categoryProducts = ref([])

const router = useRouter()
const showLoginConfirm = ref(false);
// 关闭登录确认弹窗
const closeLoginConfirm = () => {
  showLoginConfirm.value = false;
};

// 去登录
const goToLogin = () => {
  router.push({ path: "/login" });
  closeLoginConfirm();
};
const goToProductList = (productId, productName) => {
  router.push({
    name: 'ProductList', // 路由名称，需与你的路由配置一致
    params: { id: productId, name: productName } // 传递商品ID
  })
}

const handleCategoryClick = (index) => {
  selectedCategory.value = index
  // 这里可以添加加载对应分类商品的逻辑
  getCategoryProducts(index + 1)
}

const getCategoryProducts = async (id) => {
  const res = await getCategoryDetail(id)
  if (res.data.code === 200) {
    categoryProducts.value = res.data.data
  }
}

const showCart = () => {
  if (userStore.userInfo && userStore.userInfo.id) {
    router.push({
      name: 'ShoppingCart',
      params: { id: 14 }//用户id--记得换
    })
  } else {
    showLoginConfirm.value = true;
  }

}

// 拖拽相关变量
const isDragging = ref(false)
const initialX = ref(0)
const initialY = ref(0)
const currentX = ref(0)
const currentY = ref(0)
const cartButton = ref(null)

// 开始拖拽
const startDrag = (event) => {
  // 只有点击而不是拖拽时才导航到购物车
  isDragging.value = false

  // 记录初始触摸位置
  initialX.value = event.touches[0].clientX
  initialY.value = event.touches[0].clientY

  // 获取按钮当前位置
  const button = event.currentTarget
  button.classList.add('no-transition') // 禁用过渡效果以提高响应速度

  // 保存当前位置
  const buttonRect = button.getBoundingClientRect()
  currentX.value = buttonRect.left
  currentY.value = buttonRect.top
}

// 拖拽中
const onDrag = (event) => {
  // 如果移动超过一定距离，标记为拖拽而不是点击
  const touchX = event.touches[0].clientX
  const touchY = event.touches[0].clientY

  const deltaX = Math.abs(touchX - initialX.value)
  const deltaY = Math.abs(touchY - initialY.value)

  // 如果移动超过3px，认为是拖拽（降低阈值提高灵敏度）
  if (deltaX > 3 || deltaY > 3) {
    isDragging.value = true

    const button = event.currentTarget
    button.classList.add('dragging')

    // 直接使用触摸点位置计算，减少计算延迟
    const buttonWidth = button.offsetWidth
    const buttonHeight = button.offsetHeight

    // 计算新位置（手指位置减去按钮尺寸的一半，使按钮中心跟随手指）
    const newLeft = touchX - buttonWidth / 2
    const newTop = touchY - buttonHeight / 2

    // 限制在屏幕内
    const windowWidth = window.innerWidth
    const windowHeight = window.innerHeight

    const boundedLeft = Math.max(0, Math.min(newLeft, windowWidth - buttonWidth))
    const boundedTop = Math.max(0, Math.min(newTop, windowHeight - buttonHeight))

    // 更新按钮位置（使用transform而不是left/top属性，提高性能）
    button.style.transform = `translate3d(${boundedLeft}px, ${boundedTop}px, 0)`
    button.style.left = '0'
    button.style.top = '0'
    button.style.right = 'auto'
    button.style.bottom = 'auto'

    // 阻止默认行为和事件冒泡
    event.preventDefault()
    event.stopPropagation()
  }
}

// 结束拖拽并吸附
const endDrag = (event) => {
  const button = event.currentTarget
  button.classList.remove('no-transition') // 恢复过渡效果

  if (isDragging.value) {
    isDragging.value = false
    button.classList.remove('dragging')

    // 获取当前位置
    const buttonRect = button.getBoundingClientRect()
    const windowWidth = window.innerWidth
    const windowHeight = window.innerHeight

    // 重置transform
    button.style.transform = 'none'

    // 计算是否应该吸附到左侧或右侧
    const buttonCenterX = buttonRect.left + buttonRect.width / 2

    // 设置垂直位置（保持在当前高度，但不超出屏幕）
    const safeTop = Math.max(20, Math.min(buttonRect.top, windowHeight - buttonRect.height - 20))
    button.style.top = `${safeTop}px`
    button.style.bottom = 'auto'

    if (buttonCenterX < windowWidth / 2) {
      // 吸附到左侧
      button.style.left = '20px'
      button.style.right = 'auto'
    } else {
      // 吸附到右侧
      button.style.right = '20px'
      button.style.left = 'auto'
    }

    // 阻止点击事件
    event.stopPropagation()
    return false
  }
}

// 添加点击处理函数，只有在非拖拽状态下才导航
const handleCartClick = (event) => {
  if (!isDragging.value) {
    showCart()
  }
}

onMounted(async () => {
  const res = await getCategoryList()
  if (res.data.code === 200) {
    categoryList.value = res.data.data
    selectedCategory.value = 0
  }
  getCategoryProducts(selectedCategory.value + 1)
})
</script>

<style lang="scss" scoped>
// 变量定义
$gray-light: #b9a8ff;
$gray: #f1edfe;
$gray-dark: #d0d0d0;
$white: #f8e1ff;

// 全局样式
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;

}

// 移动应用容器
.mobile-app {
  width: 100%;
  height: 100vh;
  display: flex;
  flex-direction: column;
  max-width: 480px;
  margin: 0 auto;
  position: relative;
  overflow: hidden;
}

// 现代化配色
$primary-gradient-start: #7C4DFF;
$primary-gradient-end: #651FFF;
$header-text: #FFFFFF;
$header-shadow: rgba(124, 77, 255, 0.2);

.header {
  position: relative;
  width: 100%;
  height: 64px;
  background: linear-gradient(135deg, $primary-gradient-start, $primary-gradient-end);
  overflow: hidden;

  .header-content {
    position: relative;
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 0 16px;
    z-index: 2;

    h1 {
      color: $header-text;
      font-size: 1.25rem;
      font-weight: 600;
      letter-spacing: 0.5px;
      text-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
      position: relative;

      // 添加文字动画效果
      animation: titleFadeIn 0.8s ease-out;

      &::after {
        content: '';
        position: absolute;
        bottom: -4px;
        left: 50%;
        transform: translateX(-50%);
        width: 24px;
        height: 2px;
        background-color: $header-text;
        border-radius: 1px;
        opacity: 0.8;
        transition: width 0.3s ease;
      }

      &:hover::after {
        width: 40px;
      }
    }
  }

  // 毛玻璃效果背景
  .header-blur {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: linear-gradient(135deg,
        rgba(255, 255, 255, 0.1),
        rgba(255, 255, 255, 0.05));
    backdrop-filter: blur(10px);
    -webkit-backdrop-filter: blur(10px);
    z-index: 1;
  }

  // 添加动态光效
  &::before {
    content: '';
    position: absolute;
    top: -50%;
    left: -50%;
    width: 200%;
    height: 200%;
    background: radial-gradient(circle,
        rgba(255, 255, 255, 0.1) 0%,
        rgba(255, 255, 255, 0) 70%);
    animation: rotateGradient 15s linear infinite;
    z-index: 1;
  }

  // 添加底部阴影
  &::after {
    content: '';
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 4px;
    background: linear-gradient(90deg,
        transparent,
        rgba(255, 255, 255, 0.2),
        transparent);
    z-index: 3;
  }
}

// 标题淡入动画
@keyframes titleFadeIn {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }

  to {
    opacity: 1;
    transform: translateY(0);
  }
}

// 背景光效旋转动画
@keyframes rotateGradient {
  from {
    transform: rotate(0deg);
  }

  to {
    transform: rotate(360deg);
  }
}

// 响应式适配
@media (max-width: 360px) {
  .header {
    height: 56px;

    .header-content h1 {
      font-size: 1.1rem;
    }
  }
}

// 内容区域
.content {
  display: flex;
  flex: 1;
  overflow: hidden;
}

// 变量定义
$jelly-purple: #362a5a;
$jelly-dark-purple: #3f06ec;
$jelly-light-purple: #f1edfe;

$border-color: #9d89f7;

$primary-purple: #ffffff;
$light-purple: #fbebff;
$dark-purple: #ffffff;

// 侧边栏基础样式
.sidebar {
  width: 100px;
  height: 100%;
  background: linear-gradient(180deg, #FFFFFF 0%, #F8F7FF 100%);
  overflow-y: auto;
  padding: 12px 8px;
  box-shadow: 2px 0 20px rgba(124, 77, 255, 0.08);
  position: relative;
  z-index: 10;

  // 自定义滚动条
  &::-webkit-scrollbar {
    width: 4px;
  }

  &::-webkit-scrollbar-track {
    background: #F8F7FF;
  }



  .category-list {
    list-style: none;
    display: flex;
    flex-direction: column;
    gap: 10px;

    .category-item {
      padding: 14px 8px;
      font-size: 13px;
      font-weight: 500;
      text-align: center;
      cursor: pointer;
      position: relative;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      background: #FFFFFF;
      border-radius: 12px;
      color: #666666;
      box-shadow: 0 2px 8px rgba(124, 77, 255, 0.06);
      border: 1px solid rgba(124, 77, 255, 0.1);
      overflow: hidden;

      // 背景动画效果
      &::before {
        content: '';
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background: linear-gradient(45deg, #7C4DFF, #B388FF);
        opacity: 0;
        transition: opacity 0.3s ease;
        z-index: -1;
      }

      &:hover {
        transform: translateY(-2px);
        box-shadow: 0 4px 12px rgba(124, 77, 255, 0.12);
        border-color: rgba(124, 77, 255, 0.2);
      }

      &.active {
        color: #FFFFFF;
        transform: scale(1.02);
        border-color: transparent;
        background: linear-gradient(45deg, #7C4DFF, #B388FF);
        box-shadow: 0 4px 15px rgba(124, 77, 255, 0.25);

        // 活跃状态指示器
        &::after {
          content: '';
          position: absolute;
          right: -2px;
          top: 50%;
          transform: translateY(-50%);
          width: 4px;
          height: 20px;
          background: #FFFFFF;
          border-radius: 2px;
          animation: indicatorPulse 1.5s infinite;
        }
      }

      // 文字溢出处理
      span {
        display: block;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;
      }
    }
  }
}

// 活跃指示器动画
@keyframes indicatorPulse {
  0% {
    opacity: 0.6;
    height: 20px;
  }

  50% {
    opacity: 1;
    height: 24px;
  }

  100% {
    opacity: 0.6;
    height: 20px;
  }
}

// 响应式调整
@media (max-width: 360px) {
  .sidebar {
    width: 90px;
    padding: 10px 6px;

    .category-list .category-item {
      padding: 12px 6px;
      font-size: 12px;
    }
  }
}

// 产品网格
.product-grid {
  flex: 1;
  margin: 5px;
  display: grid;
  grid-template-columns: repeat(3, minmax(70px, 1fr));
  grid-auto-rows: 110px; // 固定行高保持对齐
  grid-gap: 8px; // 减少间隙
  overflow-y: auto;
  width: 100%;
  background: #fff;


  .product-item {
    width: 100%; // 使用百分比填充网格单元
    height: 100%;
    min-width: 70px; // 最小宽度限制

    border-radius: 4px;
    border-radius: 4px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    box-sizing: border-box;
    position: relative;

    &-title {
      margin-top: 5px;
      font-size: 12px;
      padding: 0 2px;
      width: 100%;
      text-align: center;
      white-space: nowrap; // 单行显示
      overflow: hidden;
      text-overflow: ellipsis; // 文字过长显示省略号
    }

    &-image {
      width: 80px;
      height: 80px;
      display: flex;
      align-items: center;
      justify-content: center;
      background: $gray;
      border-radius: 4px;

      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
        border-radius: 4px;
      }
    }
  }
}

// 底部
.footer {
  height: 50px;
  background-color: $gray-light;
  border-top: 1px solid $gray;
}

.cart-block {
  width: 56px;
  height: 56px;
  background: linear-gradient(135deg, #f5f2ff, #e7ddff);
  border-radius: 50%;
  display: flex;
  justify-content: center;
  align-items: center;
  position: fixed;
  bottom: 80px;
  right: 20px;
  cursor: pointer;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4px 12px rgba(124, 77, 255, 0.25);
  color: #FFFFFF;
  font-size: 14px;
  font-weight: 500;
  z-index: 100;
  touch-action: none;
  /* 防止触摸事件被浏览器处理 */
  user-select: none;
  /* 防止文本选择 */
  will-change: transform;
  /* 提示浏览器优化变换性能 */

  &.no-transition {
    transition: none !important;
  }

  // 添加内部光晕效果
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: radial-gradient(circle at center, rgba(255, 255, 255, 0.1) 0%, rgba(255, 255, 255, 0) 70%);
    border-radius: 50%;
    opacity: 0;
    transition: opacity 0.3s ease;
  }

  &:hover {
    transform: translateY(-4px) scale(1.05);
    box-shadow: 0 6px 16px rgba(124, 77, 255, 0.35);

    &::before {
      opacity: 1;
    }
  }

  &:active {
    transform: translateY(-2px) scale(0.98);
    box-shadow: 0 3px 8px rgba(124, 77, 255, 0.2);
  }

  // 添加涟漪动画效果
  &::after {
    content: '';
    position: absolute;
    width: 100%;
    height: 100%;
    border-radius: 50%;
    border: 2px solid #7C4DFF;
    animation: ripple 1.5s ease-out infinite;
    opacity: 0;
  }

  // 拖拽时的样式
  &.dragging {
    opacity: 0.9;
    box-shadow: 0 8px 20px rgba(124, 77, 255, 0.4);
    transform: scale(1.1);
    transition: box-shadow 0.2s ease, opacity 0.2s ease;
  }

  svg {
    pointer-events: none;
    /* 确保SVG不会干扰触摸事件 */
  }
}

@keyframes ripple {
  0% {
    transform: scale(1);
    opacity: 0.4;
  }

  100% {
    transform: scale(1.4);
    opacity: 0;
  }
}

// 响应式设计
@media (max-width: 360px) {
  .product-grid {
    grid-template-columns: repeat(2, 1fr);
  }
}

.login-confirm-overlay {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 2000;
}

.login-confirm-dialog {
  width: 80%;
  max-width: 300px;
  background-color: white;
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.login-confirm-content {
  padding: 20px;
}

.login-confirm-title {
  font-size: 18px;
  font-weight: bold;
  margin-bottom: 10px;
  text-align: center;
  color: #333;
}

.login-confirm-text {
  font-size: 14px;
  margin-bottom: 20px;
  text-align: center;
  color: #666;
}

.login-confirm-buttons {
  display: flex;
  justify-content: space-between;
}

.login-btn {
  flex: 1;
  margin-right: 10px;
  padding: 10px 0;
  background-color: #dbd2f1;
  color: white;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: bold;
  cursor: pointer;
}

.cancel-btn {
  flex: 1;
  padding: 10px 0;
  background-color: #f5f5f5;
  color: #666;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
}
</style>
